package com.module.overview.ui.cardHistoryDetails

import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.CountDownTimer
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.Window
import android.view.WindowManager
import com.common.app.data.bean.CommonMeasureResultModel
import com.common.app.data.bean.KeyEvents
import com.common.app.utls.TimeUtils.getHourMinute
import com.common.app.utls.TimeUtils.getTimeDateLong
import com.common.base.app.extras.*
import com.common.base.listener.AlertDialogConfirmBtnListener
import com.common.base.utils.AppUtils
import com.common.base.utils.SpanUtils
import com.common.base.utils.ToastUtils
import com.common.base.utils.ViewUtils
import com.common.base.utils.ViewUtils.getColor
import com.common.base.utils.ViewUtils.getDrawable
import com.common.base.utils.ViewUtils.getString
import com.common.base.widget.CustomDialog
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.db.table.UserBloodOxygen
import com.module.ble.db.table.UserBodyTemperature
import com.module.ble.db.table.UserHeartRate
import com.module.ble.listener.CusConnectBleDeviceExpandListener
import com.module.ble.listener.CusSynthesisHealthExpandListener
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.CommonCusHealthType
import com.module.overview.R
import com.module.overview.databinding.OverviewDialogInMeasurementLayoutBinding
import kotlinx.coroutines.*

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/07/16
 *
 * 描述：测量中弹框
 *
 * 修订历史：
 *
 */
class InMeasurementDialog(context: Context) :
    Dialog(context), View.OnClickListener, CusConnectBleDeviceExpandListener,
    CusSynthesisHealthExpandListener {

    private var binding: OverviewDialogInMeasurementLayoutBinding? = null

    /**
     *
     */
    private val mContext: Context

    /**
     * 点击监听
     */
    private var listener: OnInMeasurementListener? = null

    var isComplete = false
    private var mMaxCountDown = 75 * 1000L
    private var mBtnCountDownTimer: CountDownTimer? = null

    private var measurementType = 1

    var twoBtnDialog: CustomDialog? = null

    var curCheckValue =""
    var curCheckTime = 0L//此次测量时长

    /**
     * +
     * 构造方法
     *
     * @param context
     */
    init {
        setDialogTheme()
        setCanceledOnTouchOutside(false)
        mContext = context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = OverviewDialogInMeasurementLayoutBinding.inflate(LayoutInflater.from(context))
        binding?.root?.let { setContentView(it) }

        binding?.tvMeasure?.setOnClickListener(onClick = this)

        val dialogBuilder = CustomDialog.Builder(mContext)

        // 设置标题文字
        dialogBuilder.setTitle(getString(R.string.ble_health_check_cancel))

        // 设置提示栏文
        dialogBuilder.setMessage(getString(R.string.ble_health_check_cancel_body))
        dialogBuilder.setConstraint(true)

        // 左键点击事件
        dialogBuilder.setPositiveButton(
            getString(R.string.cancel_btn_zh2)
        ) { dialog, which ->
            dialog.dismiss()
        }

        // 右键点击事件
        dialogBuilder.setNegativeButton(
            getString(R.string.ok_btn_zh)
        ) { dialog, which ->
            // 返回到当前页面
            AizoSDKUtil.instantMeasurement(measurementType, 2)
            dismiss()
            dialog.dismiss()
        }
        // 执行操作
        twoBtnDialog = dialogBuilder.create()

    }

    override fun onClick(view: View) {

        binding?.apply {
            if (tvMeasure == view) {
                when (tvMeasure.text.toString()) {
                    getString(R.string.cancel_btn_zh) -> {

                        if (twoBtnDialog?.isShowing == false) {
                            twoBtnDialog?.show()
                        }
                    }
                    getString(R.string.overview_remeasure_measuring_hint) -> {

                        binding?.tvMeasure?.text = getString(R.string.cancel_btn_zh)
                        listener?.onInMeasurementClick()
                        if (!AizoSDKUtil.isConnect()) {
                            measurementFailure()
                            return
                        }
                        createCountDownTimer()
                        AizoSDKUtil.instantMeasurement(measurementType)
                    }
                    getString(R.string.ok_btn_zh4) -> {
                        dismiss()
                    }
                }
            }

        }

    }

    override fun show() {
        super.show()
        //获取当前Activity所在的窗体
        val dialogWindow = window
        //设置Dialog从窗体底部弹出
        dialogWindow?.setGravity(Gravity.CENTER)
        dialogWindow?.decorView?.setPadding(0, 0, 0, 0)
        val lp = dialogWindow?.attributes
        //设置宽
        lp?.width = WindowManager.LayoutParams.MATCH_PARENT
        //设置高
        lp?.height = WindowManager.LayoutParams.WRAP_CONTENT
        dialogWindow?.attributes = lp
        //显示对话框
        dialogWindow?.setGravity(Gravity.CENTER)
        //设置dialog的动画效果
        dialogWindow?.setWindowAnimations(R.style.bottomShowStyle)

        AizoSDKUtil.addConnectBleDeviceExpandListener(this)
        AizoSDKUtil.addSynthesisHealthExpandListener(this)
    }

    override fun dismiss() {
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer = null
        AizoSDKUtil.removeSynthesisHealthExpandListener(this)
        AizoSDKUtil.removeConnectBleDeviceExpandListener(this)
        AizoSDKUtil.instantMeasurement(measurementType, 2)
        super.dismiss()
    }

    fun show(mType: Int = 0) {
        measurementType = mType

        show()

        if (!AizoSDKUtil.isConnect()) {
            measurementFailure()
            return
        }
        createCountDownTimer()
        AizoSDKUtil.instantMeasurement(measurementType)

    }

    private fun createCountDownTimer() {
        isComplete = false
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer = null
        mBtnCountDownTimer = object : CountDownTimer(mMaxCountDown, 1000L) {
            override fun onTick(millisUntilFinished: Long) {
            }

            override fun onFinish() {
                twoBtnDialog?.dismiss()
                binding?.totalAnim?.visibility = GONE
                binding?.tvMeasure?.isEnabled = true
                binding?.animCountdown?.pauseAnimation()
                isComplete.yes {
                    binding?.totalInMeasurement?.visibility = VISIBLE
                    when(measurementType){
                        CommonCusHealthType.BLOODOXYGEN.value->binding?.title?.text = getString(R.string.overview_in_measurement_oxy_result_hint)
                        else ->binding?.title?.text = getString(R.string.overview_in_measurement_hr_result_hint)
                    }
                    binding?.totalMeasurementResult?.visibility = VISIBLE
                    binding?.tvMeasure?.text = getString(R.string.ok_btn_zh4)
                    binding?.tvMeasure?.setTextColor(getColor(R.color.white))
                    binding?.tvMeasure?.background = getDrawable(R.drawable.bg_round_product_100)
                    val unTemp = when(measurementType){
                        CommonCusHealthType.BLOODOXYGEN.value->getString(R.string.common_heart_rate_unit)
                        CommonCusHealthType.BODYTEMP.value->getString(R.string.common_ssd_unit)
                        else ->"${getString(R.string.common_once_hint)}/${getString(R.string.common_minutes_hint)}"}

                    binding?.tvMeasurementResult?.apply {
                        SpanUtils.create()
                            .addForeColorSection(curCheckValue, getColor(R.color.c_191919))
                            .setAbsSize(curCheckValue, 32)
                            .setStyle(curCheckValue, Typeface.BOLD)
                            .addSection(unTemp)
                            .showIn(this)
                    }

                    binding?.tvMeasurementResultTime?.text = "${getString(R.string.common_last_time_hint)}  ${getHourMinute(curCheckTime)}"
                }.otherwise {
                    binding?.tvFailureHint?.visibility = VISIBLE
                    measurementFailure()
                }
            }
        }

//        binding?.tvMeasure?.isEnabled = false
        binding?.tvMeasure?.text = getString(R.string.cancel_btn_zh)
        binding?.tvMeasure?.setTextColor(getColor(R.color.c_7f7f7f))
        binding?.tvMeasure?.background = getDrawable(R.drawable.bg_round_e6e6e6_100)

        when(measurementType){
            CommonCusHealthType.BLOODOXYGEN.value->{
                binding?.animCountdown?.setAnimation("overview_anim_blood_oxygen.json")//通过AE生成的图文件(json格式)
                binding?.title?.text = getString(R.string.overview_in_measurement_oxy_hint)
            }
//            CommonCusHealthType.BODYTEMP.value->
            else ->{
                binding?.animCountdown?.setAnimation("overview_anim_heart_rate.json")//通过AE生成的图文件(json格式)
                binding?.title?.text = getString(R.string.overview_in_measurement_hr_hint)
            }
        }

        mBtnCountDownTimer?.start()
        binding?.totalInMeasurement?.visibility = VISIBLE
        binding?.totalMeasurementResult?.visibility = GONE
        binding?.tvFailureHint?.visibility = GONE
        binding?.totalAnim?.visibility = VISIBLE
        binding?.animCountdown?.playAnimation()
    }

    fun measurementFailure() {
        binding?.totalInMeasurement?.visibility = GONE
        when(measurementType){
            CommonCusHealthType.BLOODOXYGEN.value->binding?.title?.text = "${getString(R.string.overview_in_measurement_oxy_hint)}${getString(R.string.common_prompt_zh)}"
            else ->binding?.title?.text = "${getString(R.string.overview_signs_measure_hr_hint)}${getString(R.string.common_prompt_zh)}"
        }

        binding?.tvMeasure?.text = getString(R.string.overview_remeasure_measuring_hint)
        binding?.tvMeasure?.setTextColor(getColor(R.color.white))
        binding?.tvMeasure?.background = getDrawable(R.drawable.bg_round_product_100)
    }


    /**
     * set dialog theme(设置对话框主题)
     */
    private fun setDialogTheme() {
        requestWindowFeature(Window.FEATURE_NO_TITLE) // android:windowNoTitle
        window!!.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND) // android:backgroundDimEnabled默认是true的
        window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) // android:windowBackground
    }

    /**
     * @param listener
     */
    fun setListener(listener: OnInMeasurementListener?) {
        this.listener = listener
    }

    /**
     *
     */
    interface OnInMeasurementListener {
        fun onInMeasurementClick()
    }

    override fun onConnect(macStr: String?) {
    }

    override fun onConnectError(macStr: String?, throwable: Throwable?, state: Int) {
        measurementFailure()
        isComplete = false
    }

    override fun onDisconnect(macStr: String?) {
        measurementFailure()
        isComplete = false
    }

    override fun onHandleDevice(type: Int, result: Boolean) {
    }

    override fun onBoundDeviceResult(macStr: String, result: Boolean) {
    }

    override fun onLatestHr(value: Int, macStr: String, time: Long) {
    }

    override fun onHeartRateDataListResult(result: List<UserHeartRate>) {
    }

    override fun getLatestBloodOxygen(value: Int, macStr: String, time: Long) {
    }

    override fun onBloodOxygenDataListResult(result: List<UserBloodOxygen>) {
    }

    override fun onLatestBodyTemper(value: Float, macStr: String, time: Long) {
    }

    override fun onBodyTemperDataListResult(result: List<UserBodyTemperature>) {
    }

    override fun onMeasureResult(
        result: Boolean,
        type: Int,
        time: Long,
        heartRate: Int,
        bloodOxygen: Int,
        bodyTemp: Float,
        envTemp: Float
    ) {
        isComplete = result
        curCheckTime = time

        when (type) {
            1 -> {
                curCheckValue = heartRate.toString()
                LiveEventBus.get(KeyEvents.KEY_MEASURE_HVO_RESULT).post(CommonMeasureResultModel(measureType = type, value = heartRate))
            }
            2 -> {
                curCheckValue = bloodOxygen.toString()
                LiveEventBus.get(KeyEvents.KEY_MEASURE_HVO_RESULT).post(CommonMeasureResultModel(measureType = type, value = bloodOxygen))
            }
            6 -> {
                curCheckValue = bodyTemp.formatToFloat(1).toString()
                LiveEventBus.get(KeyEvents.KEY_MEASURE_HVO_RESULT).post(CommonMeasureResultModel(measureType = type, value = bodyTemp.formatToFloat(1)))
            }
        }
        mBtnCountDownTimer?.cancel()
        mBtnCountDownTimer?.onFinish()
        mBtnCountDownTimer= null
    }
}